<?php

session_start();
$action = isset($_GET["action"]) ? $_GET["action"] : "register";

require_once ("conf/conf.php");
require_once ("locales/ro.php");
require ("include/function.php");

if($action == 'register'){
    echo doRegister();
} else if($action == 'verify'){
    doVerifyRegister();
}


/**
 * @return string
 */
function doRegister(){
    $success = false;
    // TODO verify $email for SQL Injection
    $email = isset($_POST["username"]) ? trim($_POST["username"]) : "";
    $password = isset($_POST["password"]) ? $_POST["password"] : "";
    $error = '';

    // TODO verify for valid email
    if ($email != "" && $password != "") { // TODO verify more
        $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);

        // verify if email exists
        $sql = "SELECT id, status, activationkey FROM users WHERE email = '$email'";
        $r = do_query($sql);
        $total = mysql_fetch_array($r);
        if($total){
            $error = REGISTER_FAILED_EMAIL_EXISTS;
            if($total[1] == 'verify'){
                // sent email again
                $mail = sentRegisterMail($email, $total[2]);
            }
        } else {
            $password = md5($password);
            $key =  getNewKey($email);

            $mail = sentRegisterMail($email, $key);

            if($mail['success']){

                $sql = "INSERT INTO users (email, password, status, activationkey)".
                        "VALUES ('$email', '$password', 'verify', '$key')";

                // insert in DB
                $r = do_query($sql);
                if($r){
                    $success = true;
                } else {
                    // TODO error message
                }
            } else {
                $error = $mail['message'];
            }
        }
        db_disconnect($connection);
    }

    if($success){
        return renderSuccess(str_replace("{0}", $email, REGISTER_VERIFY_EMAIL_MSG), REGISTER_SUCCESS_TITLE);
    } else {
        return renderError($error, REGISTER_FAILED_TITLE);
    }
}


/**
 * @param  $emailTo
 * @param  $key
 * @return array (JSON Array)
 */
function sentRegisterMail($emailTo, $key){

    $siteName = $_SERVER['HTTP_HOST'];

    // TODO use register-msg-ro.html
    //$body             = file_get_contents('include/register-msg-ro.html');
    //$body             = eregi_replace("[\]",'',$body);

    $url = "http://$siteName/register.php?action=verify&key=$key";
    // EN
//    $body = "Welcome to our website!<br/>".
//            "You, or someone using your email address, has completed registration at $siteName.<br/>".
//            "You can complete registration by clicking the following link: <br/>".
//            "<a href=\"$url\" target=\"_blank\">$url</a><br/>".
//            "If this is an error, ignore this email and you will be removed from our mailing list.<br/>".
//            "Regards, $siteName Team";

    // RO
    $body = "Bine aţi venit pe site-ul nostru!<br/>".
            "Dumneavoastră, sau altcineva a utilizat email-ul dvs. şi a început înregistrarea pe $siteName.<br/>".
            "Puteţi completa înregistrarea accesând următorul link: <br/><br/>".
            "<a href=\"$url\" target=\"_blank\">$url</a><br/><br/>".
            "Dacă nu dumneavoastră aţi completat înregistrarea, ignoraţi acest email.<br/>".
            "Binecuvantări, Echipa $siteName";

    $subject = "$siteName Registration";

    return sentMail($emailTo, $subject, $body);
}


/**
 * @return void
 */
function doVerifyRegister(){
    $key = $_GET["key"];
    if($key){
        $connection = db_connect(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);
        $sql = "SELECT id, email FROM users WHERE activationkey = '$key' AND status = 'verify'";
        $r = do_query($sql);
        $total = mysql_fetch_array($r);
        if($total){
            $userId = $total[0];

            //            $sql="UPDATE users SET activationkey = '', status='active' WHERE id = $userId";
            $sql="UPDATE users SET status='active' WHERE id = $userId";
            $r = do_query($sql);
            onLogin($userId, $total[1]);
            header("Location: /");
            //exit;
        } else {
            $siteName = $_SERVER['HTTP_HOST'];
            header("Refresh: 3; /");
            echo "nu exista acest key de activare<br/>".
                    "<a href=\"/\">$siteName</a>";
        }
        db_disconnect($connection);
    }
}